<template>
  <h3>注册</h3>
  <van-form @submit="reg">
    <van-cell-group inset>
      <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]" />
      <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]" />
      <van-field v-model="repPassword" type="password" name="密码" label="确认密码" placeholder="重新输入密码"
        :rules="[{ required: true, message: '请重新输入密码' }]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit"> 
        注册
      </van-button>
    </div>
  </van-form>
  <p class="login" @click="login">登录</p>
</template>

<script setup lang='ts'>
import { ref } from 'vue';
import axios from '../utils/http';
import { userInfo } from '../types/login'
import { useRouter } from 'vue-router';
const loginOutStatus = ref()
const loginOutMessage = ref('')
const router = useRouter()
const password = ref('')
const username = ref('')
const repPassword = ref('')
const onSubmit = async () => {
  const res = await axios.post<userInfo>('users/register', {
    userpwd: password.value,
    username: username.value
  })
  loginOutStatus.value = res.status 
  loginOutMessage.value = res.message
  console.log(res)
};
const reg = async()=>{
  const userRegex = /^[a-zA-Z0-9]{6,12}$/
  const psdRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/
  if (!userRegex.test(username.value)) {
    alert('用户名输入格式不正确！');
    return;
  }
  if (!psdRegex.test(password.value)) {
    alert('输入的密码格式不正确！');
    return;
  }
  if (repPassword.value !== password.value) {
    alert('两次输入的密码不一致，请重新输入！');
    return;
  }
  await onSubmit()
  if (loginOutStatus.value === 201) {
        alert('注册成功！');
        router.push('/login'); 
    } else {
        alert(`${loginOutMessage.value}`); 
    }
}
const login = ():void=>{
  router.push('/login')
}
</script>

<style>
  .login{
    display: flex;
    justify-content: end;
    margin-right: 15px;
    color: #1989fa;
  }
</style>